import React, { Component } from 'react'
import {FlatList, TouchableOpacity, Image, StyleSheet,  Text, View, Dimensions} from 'react-native'
import { getNewsList} from '../../utils/api';
import {   } from 'react-native-gesture-handler';
import Loading from '../../components/Loading';
import Ionicons from 'react-native-vector-icons/Ionicons';
export class Index extends Component {
  constructor() {
    super();
    this.state = {
      type: 'top',
      list: [],
      types:[
        {key: 'top', title: '头条'},
        {key: 'shehui', title: '社会'},
        {key: 'guonei', title: '国内'},
        {key: 'guoji', title: '国际'},
        {key: 'yule', title: '娱乐'},
        {key: 'tiyu', title: '体育'},
        {key: 'junshi', title:  '军事'},
        {key: 'keji', title: '科技'},
        {key: 'caijing', title: '财经'},
        {key: 'shishang', title: '时尚'}
      ],
      initialTypeIndex: 0
    }
  }
  componentDidMount = () => {
    this.getList();
  }
  getList = () => {
    const type = this.state.type;
    getNewsList(type).then(res => {
      // console.error(res , '请求')
      this.setState({
        list: res
      })
    }).catch(err => {
      console.error(JSON.stringify(err))
    });
  }
  newsItemThreeImages = ({item, index}) => {
    if(item.thumbnail_pic_s02 && item.thumbnail_pic_s03) {
      return this.newsItemThreeImages();
    }
  }
  sigleImage = ({item, index}) => {
    return (<TouchableOpacity
      onPress={() => alert(item.url)}
      >
      <View style={[styles.newsItemContainer]}>
        <View  style={[styles.newsItem1Text]}>
          <Text style={[styles.newsItem1Title]} numberOfLines={2}>{item.title}</Text>
          <View  style={[styles.newsItem1Footer]}>
            <Text style={[styles.newsItem1Meta]}>
              {item.date} {item.author_name}
            </Text>
            <Ionicons name={'heart-outline'} size={18} />
          </View>
        </View>
        { item.thumbnail_pic_s ? <Image
            source={{uri: item.thumbnail_pic_s}}
            style={[styles.newsItem1Image]}
          /> : ''}
       
      </View>
    </TouchableOpacity>)
  }
  newsItem = ({item, index}) => {
    if(item.thumbnail_pic_s02 && item.thumbnail_pic_s03) {
      // return this.newsItemThreeImages({item, index});
    } else {
      return this.sigleImage({item, index});
    }
  }
  
  newsType = ({index, item})=> {
    let isActive = item.key == this.state.type;
    return (
      <TouchableOpacity onPress={()=> {
        if(index === this.state.initialTypeIndex) return;
        this.lastIndex = this.state.initialTypeIndex;
        this.setState({
          initialTypeIndex: index,
          type: item.key
        }, ()=> {
          // this._flatList.current.scrollToIndex({ viewPosition: 0, index: this.state.initialTypeIndex });
          
          this._flatList.scrollToIndex({ viewPosition: 0, index: this.state.initialTypeIndex });
          // this.getList();
        })
        
      }}>
        <View style={{width: 65, height: 46, padding: 10, 
          backgroundColor: isActive ? '#dfb' : '#fff'}}>
          <Text style={{
            fontSize: 18, fontWeight: '600', textAlign:'center'}}
          >{item.title}</Text>
        </View>
      </TouchableOpacity>
    )
  }
  render() {
    return (
      <>
        {
          this.state.list.length ?
          <FlatList 
            data={this.state.list}
            renderItem={this.newsItem} 
            keyExtractor={item => item.uniquekey}
            showsHorizontalScrollIndicator={false}
            ListHeaderComponent={()=> {
              return <FlatList 
                 horizontal={true}
                 data={this.state.types}
                 keyExtractor={item => item.key}
                 renderItem={this.newsType}
                 initialScrollIndex={this.state.initialTypeIndex}
                 onScrollToIndexFailed={error => console.log('scroll failed', error)}
                >
              </FlatList>
            }}
          />
          :  <FlatList 
              data={[]}
              renderItem={this.newsItem} 
              keyExtractor={item => item.uniquekey}
              showsHorizontalScrollIndicator={false}
              ListHeaderComponent={()=> {
                return <FlatList 
                  ref={el => {this._flatList = el}}
                  horizontal={true}
                  data={this.state.types}
                  keyExtractor={item => item.key}
                  renderItem={this.newsType}
                  initialScrollIndex={0}
                  //  onScrollToIndexFailed={error => console.log('scroll failed', error)}
                   getItemLayout={(param, index) => ({ length: 10, offset: 64 * index, index })} 
                  >
                </FlatList>
              }}
        />
        }
      </>
    )
  }
}
const styles = StyleSheet.create({
  newsItem1Container: {
    flexDirection: 'row', 
    justifyContent: "space-between", 
    alignItems: 'center',
    marginVertical: 10
  },
  newsItem1Text: {
    flexDirection: 'column', 
    justifyContent: "space-between", 
    width: Dimensions.get('window').width * 2/3 - 20 
  },
  newsItem1Title: {
    paddingHorizontal: 10, 
    fontSize: 18, 
    width: Dimensions.get('window').width * 2/3, 
    marginBottom: 20
  },
  newsItem1Footer: {
    flexDirection: 'row', 
    justifyContent: 'space-between',
    paddingHorizontal: 10
  },
  newsItem1Meta: {
    fontSize: 13
  },
  newsItem1Image: {
    width: Dimensions.get('window').width/3,
    height: 80,
    marginVertical: 5,
    marginHorizontal: 10
  },

  newsItemContainer: {
    flexDirection: 'row', 
    justifyContent: "space-between", 
    alignItems: 'center',
    marginVertical: 10
  },
  newsItemHeader: {
    fontSize: 18,
    width: Dimensions.get('window').width - 20,
  },
  newsItemImageContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  newsItemImage: {
    width: Dimensions.get('window').width/3-20,
    height: 80,
    marginVertical: 10
  },

  newsItemFooter: {
    // flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: '100%'
    // flexWrap: 'wrap'
  },
  
  newsItemMeta: {
    fontSize: 13
  },
})
export default Index
